from duckserver.models import User
from duckserver.models import Longplan
import time


# 创建长期计划
def createLongPlan(userid, title, targettime, endtime, alarmtime, content, focustime, relaxtime, circulate, blackhouse):
    response = {'planid': 0, 'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    plan = Longplan(userid=user, title=title, targettime=targettime, endtime=endtime, alarmtime=alarmtime,
                    content=content, focustime=focustime, relaxtime=relaxtime, circulate=circulate, blackhouse=blackhouse)
    plan.save()
    if plan.planid is not None:
        response['planid'] = plan.planid
        response['ok'] = 1

    return response


# 删除长期计划
def deleteLongPlan(userid, planid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    Longplan.objects.get(planid=planid, userid=user).delete()

    response['ok'] = 1

    return response


# 获取长期计划列表
def getLongPlanList(userid):
    response = {'data': [], 'ok': 0, 'msg': ''}

    plans = Longplan.objects.filter(userid=userid)
    now = time.time()
    for plan in plans:
        obj = {}
        obj['title'] = plan.title
        obj['planid'] = plan.planid
        obj['targettime'] = plan.targettime
        obj['studytime'] = plan.studytime
        obj['endtime'] = plan.endtime
        obj['content'] = plan.content
        obj['focustime'] = plan.focustime
        obj['alarmtime'] = plan.alarmtime
        obj['relaxtime'] = plan.relaxtime
        obj['circulate'] = plan.circulate
        obj['blackhouse'] = plan.blackhouse
        obj['isfinished'] = plan.isfinished

        # 任务超时判断
        if plan.isfinished == 0 and time.mktime(plan.endtime.timetuple()) < now:
            obj['isfinished'] = -1
            plan.isfinished = -1
            plan.save()
        response['data'].append(obj)

    response['ok'] = 1

    return response
